package com.mp3s.dc.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.mp3s.dc.service.Config;
import com.mp3s.dc.utils.Tools;

import cn.hutool.core.io.FileUtil;

@Controller
@SpringBootApplication
public class lszrz {
    
    @Autowired
    private ConfigurableApplicationContext context;

    @GetMapping("/ctl/shutdown431")
    public String shutdown() {
        SpringApplication.exit(context, () -> 0); // 调用 SpringApplication.exit() 方法
        context.close(); // 关闭 Spring 容器
        return "Application is shutting down...";
    }
    @RequestMapping("/download/ls")
    @ResponseBody
    public String ls() {
        String folderPath = Config.GetFilePath();
        File folder = FileUtil.file(folderPath);
        List<File> allFiles = Tools.getAllFilesInFolder(folder);
        // 打印所有文件的路径
        String out = "";
        for (File file : allFiles) {
            // System.out.println(file.getName());
            out += " | " + file.getName();
        }
        return out;
    }


    @GetMapping("/download/{fileName}")
    public ResponseEntity<Resource> sz(@PathVariable String fileName) {
        try {
            // 构造文件路径
            File file = new File(Config.GetFilePath()+"\\" + fileName);
            System.out.println(file.getAbsolutePath());
            if (!file.exists()) {
                return ResponseEntity.notFound().build(); // 文件不存在时返回 404
            }

            // 创建文件资源
            Resource resource = new FileSystemResource(file);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"");

            // 返回文件
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().build(); // 发生异常时返回 500
        }
    }


    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "文件为空，请重新上传！";
        }

        // 获取文件名
        String fileName = file.getOriginalFilename();

        // 创建保存文件的目录（如果不存在）
        File uploadDir = new File(Config.GetFilePath());
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 文件保存路径
        String filePath = uploadDir +"\\" + fileName;

        try {
            // 使用 Hutool 的 FileUtil 将文件写入磁盘
            FileUtil.writeBytes(file.getBytes(), filePath);
            return "文件上传成功！保存路径：" + filePath;
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败：" + e.getMessage();
        }
    }
}
